<template>
<div>
    <div class="movie-list">
        <div class="card-header">
            <el-button class="icon-btn delete-icon" icon="el-icon-delete" @click="handleDeleteAll">批量删除</el-button>
            <el-button class="icon-btn add-icon" icon="el-icon-circle-plus-outline" @click="dialogVisible = true; dialogType = 'add'">添加</el-button>
        </div>

        <div class="card-table">
            <el-table
                v-if="tableData"
                :data="tableData.list"
                @selection-change="handleSelectionChange"
                stripe
                border>
                <el-table-column type="selection" min-width="50" align="center" fixed="left"></el-table-column>
                <el-table-column type="index" min-width="50" align="center" fixed="left"></el-table-column>
                <el-table-column prop="name" label="名称" min-width="180" align="center"></el-table-column>
                <el-table-column label="分类" min-width="180" align="center">
                    <template slot-scope="scope">
                        <div>{{scope.row.movieTypes.join(' / ')}}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="country" label="国家" min-width="180" align="center"></el-table-column>
                <el-table-column label="视频地址" min-width="180" align="center">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" :content="scope.row.videoUrl" placement="top-start">
                            <span class="ellipsis link" @click="playMovie(scope.row.videoUrl)">{{scope.row.videoUrl}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="描述" min-width="180" align="center">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" :content="scope.row.summary" placement="top-start">
                            <span class="ellipsis">{{scope.row.summary}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="180" align="center">
                    <template slot-scope="scope">
                        <div>{{scope.row.createTime | timerFilter()}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template slot-scope="scope">
                        <div class="tool-box">
                            <i class="icon el-icon-edit" @click="hadnleUpdate(scope.row)"></i>
                            <i class="icon el-icon-delete" @click="hadnleDeleteOne(scope.row._id)"></i>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-pagination
            v-if="tableData"
            @current-change="currentChange"
            :current-page="tableData.pageNum"
            :page-size="10"
            layout="total, prev, pager, next, jumper"
            :total="tableData.total">
        </el-pagination>

    </div>

    <el-dialog
        title="上传视频"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
        width="600px">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="影片名称" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>

            <el-form-item label="所属地区" prop="country">
                <el-select v-model="ruleForm.country" placeholder="请选择活动区域">
                    <el-option label="中国" value="中国"></el-option>
                    <el-option label="韩国" value="韩国"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="作品标签" prop="movieTypes">
                <el-select
                    v-model="ruleForm.movieTypes"
                    multiple
                    placeholder="请选择作品标签"
                    popper-class="book-label">
                    <el-option v-for="item in movieClassifyList" :key="item" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="上传" :prop="dialogType === 'add' ? 'file' : ''">
                <input type="file" ref="file" @change="handleChange">
            </el-form-item>

            <el-form-item label="影片描述" prop="summary">
                <el-input type="textarea" v-model="ruleForm.summary"></el-input>
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>

    <div v-if="openPlayer" class="dplayer-box__wrapper"></div>
    <div v-if="openPlayer" id="dplayer"></div>
</div>
</template>

<script>
import 'dplayer/dist/DPlayer.min.css'
import DPlayer from 'dplayer'
export default {
    props: ['page'],

    data () {
        return {
            tableData: null,
            movieParams: {
                page: this.page
            },
            openPlayer: false,
            multipleSelection: [],
            dialogVisible: false,
            dialogType: 'add',
            movieClassifyList: ['爱情', '动作', '科幻', '恐怖', '悬疑'],
            ruleForm: {
                name: '',
                country: '',
                movieTypes: [],
                summary: '',
                file: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入影片名称', trigger: 'blur' }
                ],
                country: [
                    { required: true, message: '请选择所属国家', trigger: 'change' }
                ],
                movieTypes: [
                    { type: 'array', required: true, message: '请选择1~4个分类', trigger: 'blur' },
                    { type: 'array', min: 1, max: 4, message: '请选择1~4个分类', trigger: 'change' }
                ],
                summary: [
                    { required: true, message: '请输入影片描述', trigger: 'blur' }
                ],
                file: [
                    { required: true, message: '请选择视频文件', trigger: 'blur' }
                ]
            }
        }
    },

    mounted () {
        this.getMovieList()
        let _this = this
        this.$nextTick(function () {
            document.addEventListener('keyup', function (e) {
                if (e.keyCode === 27) {
                    _this.openPlayer = false
                }
            })
        })
    },

    methods: {
        // 获取视频列表
        getMovieList () {
            this.$store.dispatch('getMovieList', this.movieParams).then(res => {
                console.log(res)
                if (res.code === 200) {
                    this.tableData = res.data
                } else {
                    this.tableData = null
                }
            })
        },

        // 播放视频
        playMovie (url) {
            this.openPlayer = true
            setTimeout(() => {
                new DPlayer({
                    container: document.getElementById('dplayer'),
                    video: {
                        url: url
                    }
                })
            }, 500)
        },

        handleChange (val) {
            this.ruleForm.file = val.target.files[0]
        },

        // 新增视频
        submitForm () {
            this.$refs['ruleForm'].validate(async (valid) => {
                if (valid) {
                    let params = JSON.parse(JSON.stringify(this.ruleForm))
                    delete params.file
                    params.movieTypes = params.movieTypes.join(',')
                    if (this.dialogType === 'add') {
                        let formData = new FormData()
                        formData.append('file', this.ruleForm.file)
                        let res = await this.$store.dispatch('uploadMovieVideo', formData)
                        if (res.code === 200) {
                            params.videoUrl = res.data
                            this.$store.dispatch('addMovieList', params).then(res => {
                                if (res.code === 200) {
                                    this.dialogVisible = false
                                    this.$message({ type: 'success', message: res.msg })
                                    this.getMovieList()
                                } else {
                                    this.$message({ type: 'error', message: res.msg })
                                }
                            })
                        }
                    } else {
                        if (this.ruleForm.file) {
                            let formData = new FormData()
                            formData.append('file', this.ruleForm.file)
                            let res = await this.$store.dispatch('uploadMovieVideo', formData)
                            if (res.code === 200) {
                                params.videoUrl = res.data
                            }
                        }
                        this.$store.dispatch('updateMovieList', params).then(res => {
                            if (res.code === 200) {
                                this.dialogVisible = false
                                this.$message({ type: 'success', message: res.msg })
                                this.getMovieList()
                            } else {
                                this.$message({ type: 'error', message: res.msg })
                            }
                        })
                    }
                } else {
                    return false
                }
            })
        },

        // 修改视频信息
        hadnleUpdate (row) {
            this.dialogType = 'update'
            this.ruleForm._id = row._id
            this.ruleForm.name = row.name
            this.ruleForm.country = row.country
            this.ruleForm.movieTypes = row.movieTypes
            this.ruleForm.summary = row.summary
            this.dialogVisible = true
        },

        // 批量删除多选数组
        handleSelectionChange (val) {
            this.multipleSelection = val
        },

        // delete all
        handleDeleteAll () {
            if (this.multipleSelection.length === 0) {
                this.$message({ type: 'warning', message: '请至少选择一个！' })
            } else {
                let list = []
                for (let i in this.multipleSelection) {
                    list.push(this.multipleSelection[i]._id)
                }
                this.hadnleDeleteOne(list.join(','))
            }
        },

        // delete
        hadnleDeleteOne (ids) {
            let tip = '此操作将永久删除该视频, 是否继续?'
            if (typeof (ids) === 'string') {
                tip = '此操作将永久删除所选视频, 是否继续?'
            }
            this.$confirm(tip, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$store.dispatch('delMovieList', { ids: ids }).then(res => {
                    if (res.code === 200) {
                        this.getMovieList()
                        this.$message({ type: 'success', message: res.msg })
                    } else {
                        this.$message({ type: 'error', message: res.msg })
                    }
                })
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消删除' })
            })
        },

        // 分页
        currentChange (page) {
            this.$router.push({ params: { page: page } })
        }
    },

    watch: {
        $route: function (to, from) {
            this.movieParams.page = to.params.page
            this.getMovieList()
        },

        dialogVisible: function (val) {
            if (!val) {
                this.$refs['ruleForm'].resetFields()
                this.$refs['file'].value = ''
                this.ruleForm = {
                    name: '',
                    country: '',
                    movieTypes: [],
                    summary: '',
                    file: ''
                }
            }
        }
    }
}
</script>

<style lang="scss">
.movie-list {
    background: #fff;
    padding-bottom: 15px;
    .card-header {
        height: 42px;
        font-size: 14px;
        color: #333;
        border-bottom: 1px solid #f6f6f6;
        line-height: 42px;
        padding: 10px 15px;
        .icon-btn {
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
            font-size: 12px;
            border: none;
            color: #fff;
        }
        .delete-icon {
            background: #FF5722;
        }
        .add-icon {
            background: #009688;
        }
    }
    .card-table {
        padding: 15px;
        .icon {
            cursor: pointer;
        }
        .link {
            text-decoration: underline;
            color: blue;
            cursor: pointer;
        }
    }
}
.dplayer-box__wrapper {
    position: absolute;
    z-index: 40;
    left: 0;
    top: 0;
    background: #000;
    opacity: .7;
    width: 100%;
    height: 100%;
}
#dplayer {
    position: absolute;
    z-index: 41;
    left: 50%;
    top: 50%;
    width: 864px;
    height: 486px;
    margin-left: -432px;
    margin-top: -243px;
}
</style>
